package com.epam.facebook_client;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.epam.facebook_client.api.API;
import com.epam.facebook_client.content.contract.AppContract;
import com.epam.facebook_client.manager.ImageManager;
import com.epam.facebook_client.processor.PhotosProcessor;
import common.adapters.AbstractCursorAdapter;
import common.processor.IProcessor;

public class PhotosActivity extends BaseServiceActivity implements LoaderCallbacks<Cursor> {
	
	private static final String TAG = PhotosActivity.class.getSimpleName();

	public static final String POSITION = "position";
	public static final String LIST_PHOTOS = "list_photos";
	public static final String ID_ALBUM = "list_photos";
	
	private GridView photosGridView;
	private ImageManager imageManager;
	private String idAlbum;
	private ProgressBar progressBar;
	private String nextPageUrl;
	private int currentPosition;
	private RelativeLayout loadingBottomLayout;
	private Map<String, String> parameter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photos);
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			idAlbum = String.valueOf(extras.getLong("id"));
		} else {
			finish();
		}
		progressBar = (ProgressBar) findViewById(R.id.photos_progressBar);
		photosGridView = (GridView) findViewById(R.id.gridViewPhotos);
		loadingBottomLayout = (RelativeLayout) findViewById(R.id.loadingBottom);
		imageManager = ImageManager.get(this);

		photosGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(getApplication(), PhotosPageActivity.class);
				intent.putExtra(POSITION, position);
				intent.putExtra(ID_ALBUM, idAlbum);
				startActivity(intent);
			}
		});

		photosGridView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView abslistview, int i) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
					int totalItemCount) {
				if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
					if (!TextUtils.isEmpty(nextPageUrl)) {
						parameter = new HashMap<String, String>(3);
						parameter.put(PhotosProcessor.EXTRA_URL, nextPageUrl);
						parameter.put(PhotosProcessor.EXTRA_ALBUM_ID, idAlbum);
						parameter.put(PhotosProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
						startServiceHelper(parameter, loadingBottomLayout, PhotosProcessor.ACTION);
					}
				}
			}
		});
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(0, null, this);
		parameter = new HashMap<String, String>(3);
		parameter.put(PhotosProcessor.EXTRA_URL, API.getPhotosLink(idAlbum));
		parameter.put(PhotosProcessor.EXTRA_ALBUM_ID, idAlbum);
		parameter.put(PhotosProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
		startServiceHelper(parameter, loadingBottomLayout, PhotosProcessor.ACTION);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_photos, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_refresh:
			recreateActivity();
			break;
		case R.id.menu_add_photo:
			Intent intent = new Intent(this, PostPhotoActivity.class);
			intent.putExtra("id", idAlbum);
			startActivity(intent);
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void recreateActivity() {
		Intent intent = new Intent(this, PhotosActivity.class);
		intent.putExtra("id", Long.parseLong(idAlbum));
		startActivity(intent);
		finish();
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		progressBar.setVisibility(View.VISIBLE);
		String[] selectionArgs = { idAlbum };
		return new CursorLoader(this, AppContract.PhotosColumns.CONTENT_URI, null,
				AppContract.PhotosColumns.ALBUM_ID + " = ?", selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		progressBar.setVisibility(View.GONE);
		if (cursor.getCount() > 0) {
			currentPosition = photosGridView.getFirstVisiblePosition();
			String[] columnNames = { AppContract.PhotosColumns.PICTURE };
			int[] viewId = { R.id.photo };
			AbstractCursorAdapter adapter = new AbstractCursorAdapter(this, cursor, imageManager, viewId,
					columnNames) {

				@Override
				public void setImageNull(ImageView imageView) {
					imageView.setImageDrawable(null);
				}

				@Override
				public int getLayoutAdapterId() {
					return R.layout.adapter_photo_grid_item;
				}
			};
			photosGridView.setAdapter(adapter);
			photosGridView.setSelection(currentPosition);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
	}

	@Override
	public void onServiceResult(int requestId, Intent requestIntent, int resultCode, Bundle resultData) {
		loadingBottomLayout.setVisibility(View.GONE);
		if(getRequestId() != requestId){
			return;
		}
		switch (resultCode) {
		case IProcessor.RESULT_OK:
			nextPageUrl = resultData.getString(IProcessor.EXTRA_URL);
			break;
		case IProcessor.RESULT_ERROR:
			Exception e = (Exception) resultData.getSerializable(IProcessor.EXTRAS_ERROR);
			Log.e(TAG, "ERROR: " + e);
			Toast.makeText(this, "ERROR: " + e.getMessage(), Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		getSupportLoaderManager().initLoader(0, null, this);
		super.onConfigurationChanged(newConfig);
	}
}
